package com.guoning.office_system.controller;

import com.alibaba.fastjson.JSONArray;
import com.guoning.office_system.model.User;
import com.guoning.office_system.service.UserService;
import com.guoning.office_system.utils.*;
import com.guoning.office_system.vo.Criteria;
import com.guoning.office_system.vo.PageBean;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@CrossOrigin
@RestController
@RequestMapping("user")
public class UserController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    UserService userService;

    /**
     * 获取用户数量
     * @return
     */
    @RequestMapping(value = "/getUserCount")
    public JsonResult getUserCount(){
        JsonResult js;
        try {
            Long userCount = userService.selectUserCount();
            js = new JsonResult(Constants.STATUS_SUCCESS, "查询成功", userCount);
        }catch (Exception e){
            js = new JsonResult(Constants.STATUS_ERROR, "查询异常");
        }
        return js;
    }

    /**
     * 获取全部用户
     * @param user
     * @return
     */
    @RequestMapping(value = "/getAllUser")
    public JsonResult getAllUser(User user){
        JsonResult js;
        try {
            List<User> list = userService.selectAllUser(user);
            js = new JsonResult(Constants.STATUS_SUCCESS, "查询成功", list);
        }catch (Exception e){
            js = new JsonResult(Constants.STATUS_ERROR, "查询异常");
        }
        return js;
    }

    /**
     * 获取全部普通用户
     * @return
     */
    @RequestMapping(value = "/getAll")
    public JsonResult getAll(){
        JsonResult js;
        try {
            List<User> list = userService.selectAll();
            js = new JsonResult(Constants.STATUS_SUCCESS, "查询成功", list);
        }catch (Exception e){
            js = new JsonResult(Constants.STATUS_ERROR, "查询异常");
        }
        return js;
    }

    /**
     * 登录
     * @param request
     * @param response
     * @param session
     * @param user
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public JsonResult login(HttpServletRequest request, HttpServletResponse response, HttpSession session, User user){
        JsonResult js;
        try {
            User user1 = userService.selectUserForLogin(user);
            if(user1 != null){
                if(user1.getEnableStatus() == 2){
                    js = new JsonResult(Constants.STATUS_FAIL, "用户已被停用");
                    return js;
                }else if(user1.getEnableStatus() == 3){
                    js = new JsonResult(Constants.STATUS_FAIL, "用户已注销");
                    return js;
                }else if(user1.getEnableStatus() == 4){
                    js = new JsonResult(Constants.STATUS_FAIL, "用户已被冻结");
                    return js;
                }

                String token = TokenTools.createToken(request, user1);
                Map map = new HashMap();
                map.put("token", token);
                map.put("userData", user1);
                js = new JsonResult(Constants.STATUS_SUCCESS, "登录成功", map);
            }else {
                int num = userService.updateLoginErrorNum(user.getLoginName());
                if(num == -1){
                    js = new JsonResult(Constants.STATUS_FAIL, "该账号不存在，请检查");
                }else if(num == 5){
                    js = new JsonResult(Constants.STATUS_FAIL, "密码错误，用户已被冻结");
                }else{
                    js = new JsonResult(Constants.STATUS_FAIL, "密码错误，再错误"+(5-num)+"次账号将被冻结");
                }
            }
        }catch (Exception ex){
            ex.printStackTrace();
            js = new JsonResult(Constants.STATUS_ERROR, "登录异常", ex.getMessage());
        }
        return js;
    }

    /**
     * 登出
     * @param request
     * @param response
     * @param session
     * @return
     */
    @RequestMapping(value = "/loginout", method = RequestMethod.POST)
    public JsonResult loginout(HttpServletRequest request, HttpServletResponse response, HttpSession session){
        JsonResult js;
        try {
            TokenTools.removeToken(request, request.getHeader("Token"));
            js = new JsonResult(Constants.STATUS_SUCCESS, "登出成功");
        }catch (Exception ex){
            js = new JsonResult(Constants.STATUS_ERROR, "登出异常，请稍后再试", ex.getMessage());
        }
        return js;
    }

    /**
     * 新增用户
     * @param user
     * @return
     */
    @RequestMapping(value = "/register")
    public JsonResult register(HttpServletRequest request, User user){
        JsonResult js;
        try {
            if(user.getUserName() == null || user.getUserName() == ""
            || user.getPhone() == null || user.getPhone() == ""
            || user.getLoginName() == null || user.getLoginName() == ""
            || user.getUserCode() == null || user.getUserCode() == ""){
                return new JsonResult(Constants.STATUS_FAIL,"请检查必填项");
            }
            Pattern pattern = null;
            Matcher matcher = null;

            String phone = user.getPhone();
            String phoneRegex = "^1[3-9][0-9]{9}$";
            pattern = Pattern.compile(phoneRegex);
            matcher = pattern.matcher(phone);
            boolean phoneBool = matcher.matches();
            if(!phoneBool){
                return new JsonResult(Constants.STATUS_FAIL,"手机格式不正确");
            }

            if(user.getTelephone() != null && user.getTelephone() != ""){
                String telephone = user.getTelephone();
                String telephoneRegex = "^[0][1-9]{2,3}-[0-9]{5,10}$";
                pattern = Pattern.compile(telephoneRegex);
                matcher = pattern.matcher(telephone);
                boolean telephoneBool = matcher.matches();
                if(!telephoneBool){
                    return new JsonResult(Constants.STATUS_FAIL,"座机格式不正确");
                }
            }

            String loginName = user.getLoginName();
            String userCode = user.getUserCode();

            User selectUser = new User();
            selectUser.setLoginName(loginName);
            if(userService.selectByUser(selectUser) != 0){
                return new JsonResult(Constants.STATUS_FAIL,"登录账号已存在");
            }

            selectUser = new User();
            selectUser.setPhone(phone);
            if(userService.selectByUser(selectUser) != 0){
                return new JsonResult(Constants.STATUS_FAIL,"手机号已存在");
            }

            selectUser = new User();
            selectUser.setUserCode(userCode);
            if(userService.selectByUser(selectUser) != 0){
                return new JsonResult(Constants.STATUS_FAIL,"用户编码已存在");
            }

            User onlineUser = getUserDate(request);
            user.setCreator(onlineUser.getUserName());
            int i = userService.insertSelective(user);
            if(i != 0){
                js = new JsonResult(Constants.STATUS_SUCCESS, "添加成功", i);
            }else{
                js = new JsonResult(Constants.STATUS_FAIL, "添加失败");
            }
        }catch (Exception ex){
            js = new JsonResult(Constants.STATUS_ERROR, "添加异常", ex.getMessage());
        }
        return js;
    }

    @RequestMapping(value = "/selectByCondition")
    public JsonResult selectByCondition(@RequestParam(value = "pageIndex", defaultValue = "0") Integer pageIndex,
                                        @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                        @RequestParam(value = "userCodeOrName", defaultValue = "") String userCodeOrName){
        JsonResult js;
        try{
            PageBean pageBean = new PageBean();
            pageBean.setPageIndex(pageIndex);
            pageBean.setPageSize(pageSize);
            Criteria criteria = new Criteria();
            criteria.addExtField("userCodeOrName", userCodeOrName);
            pageBean = userService.selectByCondition(criteria, pageBean);
            js = new JsonResult(Constants.STATUS_SUCCESS, "查询成功", pageBean);
        }catch (Exception ex){
            js = new JsonResult(Constants.STATUS_ERROR, "查询异常");
        }
        return js;
    }

    @RequestMapping(value = "/selectAllUserNotHaveDepartment")
    public JsonResult selectAllUserNotHaveDepartment(HttpServletRequest request,
                                        @RequestParam(value = "pageIndex", defaultValue = "0") Integer pageIndex,
                                        @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                        @RequestParam(value = "userCodeOrName", defaultValue = "") String userCodeOrName){
        JsonResult js;
        try{
            User user = getUserDate(request);
            PageBean pageBean = new PageBean();
            pageBean.setPageIndex(pageIndex);
            pageBean.setPageSize(pageSize);
            Criteria criteria = new Criteria();
            criteria.addExtField("userCodeOrName", userCodeOrName);
            pageBean = userService.selectAllUserNotHaveDepartment(criteria, pageBean);
            js = new JsonResult(Constants.STATUS_SUCCESS, "查询成功", pageBean);
        }catch (Exception ex){
            ex.printStackTrace();
            js = new JsonResult(Constants.STATUS_ERROR, "查询异常");
        }
        return js;
    }

    /**
     * 重置密码
     * @param user
     * @return
     */
    @RequestMapping(value = "/resetPwd", method = RequestMethod.POST)
    public JsonResult resetPwd(User user){
        JsonResult js;
        try {
            user.setLoginPassword("123456a");
            user.setIsDefaultPassword(1);
            int i = userService.updateByPrimaryKeySelective(user);
            if(i == 0){
                js = new JsonResult(Constants.STATUS_FAIL, "重置失败");
            }else{
                js = new JsonResult(Constants.STATUS_SUCCESS, "重置成功");
            }
        }catch (Exception e){
            js = new JsonResult(Constants.STATUS_ERROR, "重置异常");
        }
        return js;
    }

    /**
     * 修改用户(多)
     * @param params
     * @return
     */
    @RequestMapping(value = "/updateByList", method = RequestMethod.POST)
    public JsonResult updateByList(String params){
        JsonResult js;
        try {
            List<User> list = JSONArray.parseArray(params, User.class);
            int i = userService.updateByList(list);
            if(i != 0){
                js = new JsonResult(Constants.STATUS_SUCCESS, "操作成功");
            }else {
                js = new JsonResult(Constants.STATUS_FAIL, "操作失败");
            }
        }catch (Exception e){
            js = new JsonResult(Constants.STATUS_ERROR, "操作异常");
        }
        return js;
    }

    /**
     * 修改用户(单)
     * @param user
     * @return
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public JsonResult update(User user){
        JsonResult js;
        try {
            int i = userService.updateByPrimaryKeySelective(user);
            if(i != 0){
                js = new JsonResult(Constants.STATUS_SUCCESS, "操作成功");
            }else {
                js = new JsonResult(Constants.STATUS_FAIL, "操作失败");
            }
        }catch (Exception e){
            js = new JsonResult(Constants.STATUS_ERROR, "操作异常");
        }
        return js;
    }

    /**
     * 验证密码
     * @param user
     * @return
     */
    @RequestMapping(value = "/checkPassword", method = RequestMethod.POST)
    public boolean checkPassword(User user){
        User user1 = userService.checkPassword(user.getId());
        return user1.getLoginPassword().equals(user.getLoginPassword());
    }

    /**
     * 导出通讯录
     *
     * @return
     */
    @RequestMapping(value = "/export")
    public void export(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "userCodeOrName", defaultValue = "") String userCodeOrName) throws Exception {
        User inOnlineUser = getUserDate(request);
        Criteria criteria = new Criteria();
        criteria.addExtField("id", inOnlineUser.getId());
        criteria.addExtField("userCodeOrName", userCodeOrName);
        //获取数据
        List<User> list = userService.selectByConditionForExport(criteria);

        //excel标题
        String[] title = {"序号", "编码", "姓名", "部门", "手机号", "座机", "备注"};

        //excel文件名
        String fileName = "XX公司通讯录" + ".xls";

        //sheet名
        String sheetName = "用户信息表";

        String [][] content = new String[list.size()][7];

        for (int i = 0; i < list.size(); i++) {
            content[i] = new String[title.length];
            User user = list.get(i);
            content[i][0] = String.valueOf(i+1);
            content[i][1] = user.getUserCode();
            content[i][2] = user.getUserName();
            content[i][3] = user.getDepartmentName();
            content[i][4] = user.getPhone();
            content[i][5] = user.getTelephone();
            content[i][6] = user.getRemark();
        }

        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);

        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送响应流方法
     */
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
